#include "aiserver.h"
#include "ui_aiserver.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

AIServer::AIServer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AIServer)
{
    ui->setupUi(this);
    networkManager = new QNetworkAccessManager(this);
}

AIServer::~AIServer()
{
    delete ui;
}
void AIServer::sendRequest(const QString &message) {
    QNetworkRequest request;
    request.setUrl(QUrl("https://api.deepseek.com/v1/chat/completions"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", "Bearer sk-d503d4ad0a5f43c1995687a99ab21d44"); // 替换为你的 API Key

    // 构造请求数据
    QJsonObject payload;
    payload["model"] = "deepseek-chat";
    payload["messages"] = QJsonArray{
        QJsonObject{{"role", "user"}, {"content", message}}
    };

    QNetworkReply *reply = networkManager->post(
        request,
        QJsonDocument(payload).toJson()
    );

    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        onReplyFinished(reply);
    });
}

void AIServer::onReplyFinished(QNetworkReply *reply) {
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response = reply->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
        QString aiReply = jsonDoc["choices"][0]["message"]["content"].toString();
        emit responseReceived(aiReply);
    } else {
        emit responseReceived("[错误] 请求失败: " + reply->errorString());
    }
    reply->deleteLater();
}
